// pages/position/fullTime/add/add.js
import uploadImg from '../../../../utils/uploadImg.js'
import {onRecord} from '../../../../utils/integral-record.js'
import {
  edu,
  street,
  salary,
  reward,
  workExp
} from '../../../../utils/base-data.js'
import {
  $wuxSelect,
  $wuxCalendar
} from '../../../../wux-components/index'
import {
  getLocation
} from '../../../../utils/common.js'
import {
  searchPosition
} from '../../../../utils/position.js'
import {
  payStatus
} from '../../../../utils/payStatus.js'
const config = getApp().globalData.config
const T = getApp().globalData.T
let token = ''
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isEdit: false,
    isSpecialToCreate: false, // 是否从专场新建职位跳转过来
    specialId: -1,
    positionEditId: -1, // 编辑时需要用到
    position: '',
    address: '',
    posDes: '',
    step01: true,
    isReward: false,
    rewardCount: '',
    singleRewardMoney: '',
    isRedpacket: false,
    redpacketCount: '',
    singleRedpacketMoney: '',
    isPopularize: false,
    workCompany: '',
    workCompanyId: 0,
    templateImg: '/resource/image/add_post_img.png',
    isShowCalendar: true,

    industry: {
      title: '请选择',
      value: 1
    },
    salary: {
      title: '请选择',
      value: 1
    },
    workExp: {
      title: '请选择',
      value: 1
    },
    eduExp: {
      title: '请选择',
      value: 1
    },
    street: {
      title: '请选择',
      value: 1
    },
    welfares: '请选择',
    employmentType: {
      title: '请选择',
    },
    rewardDeadLine: {
      title: '请选择',
      value: 0
    },
    location: '',
    isOpenMap: true,
    isShowPosDes: false,
    popularizeDate: '请选择',
    popularizeCount: 0,
    welfaresArray: [],
    workExpArray: [],
    popularizeList: [],
    selectedPopularizeDate: [],
    reqParam: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.origin == 'edit') {
      this.setData({
        positionEditId: options.id,
        isEdit: true
      });
      wx.setNavigationBarTitle({
        title: '编辑全职职位'
      })
    }
    if (options.origin == 'special') {
      this.data.isSpecialToCreate = true;
      this.data.specialId = options.specialId;
    }
    this.showMap();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.setData({
      platform: getApp().globalData.platform
    })
    token = getApp().globalData.token;
    this.getWelfaresArr();
    this.getPopularizelist();
    if (this.data.isEdit) {
      this.getPositionDetail();
      this.getRefundInfo();
    }
    this.getPopularizeCount();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  showMap(lt, la) {
    this.setData({
      longitude: lt || 116.397726,
      latitude: la || 39.903767,
      markers: [{
        iconPath: "/resource/image/marker.png",
        id: 0,
        longitude: lt || 116.397726,
        latitude: la || 39.903767,
        width: 20,
        height: 30
      }]
    })
  },

  /**
   * 获取剩余推广次数
   */
  getPopularizeCount() {
    T.req({
      url: config.api + 'popularize/residue',
      method: 'GET',
      data: {
        token: token
      },
      success: (res) => {
        this.setData({
          totalPopularizeCount: res.positionTopNumSum
        })
      }
    })
  },

  /**
   * 获取退款情况
   */
  getRefundInfo() {
    T.req({
      url: config.api + 'position/refund_info',
      method: 'GET',
      data: {
        positionId: this.data.positionEditId,
        token: token
      },
      success: (res) => {
        this.data.oId = res.orderId; // 订单号
        if (res.isNeedRefund) { // 能退款
          this.setData({ toRefund: true })
        } else { //不能退款
          if (res.refund == 0) { // 退款审核中
            this.setData({ isRefunding: true });
          }
          if (res.refund == 1) { // 退款审核通过
            this.setData({ passRefund: true });
          }
          if (res.refund == 2) { // 退款失败
            this.setData({ againRefund: true, failRefundText: res.refundNote });
          }
          if (res.refund == 3) {
            this.setData({ successRefund: true })
          }
        }
      }
    })
  },

  getPositionDetail() {
    T.req({
      loadTitle: '加载中...',
      url: config.api + 'position/' + this.data.positionEditId,
      method: 'GET',
      data: {
        token: token
      },
      success: (res) => {
        // 悬赏
        let _reward = res.reward;
        let redPacket = res.redPacket;
        let rewardDeadLineV = reward.filter(m => m.value == 20)[0].value
        this.setData({
          position: res.name,
          industry: {
            title: res.industry,
            value: res.industryId
          },
          salary: {
            title: salary[res.salaryRange].title,
            value: res.salaryRange
          },
          workExp: {
            title: res.candidateRequire,
            value: res.candidateRequireId
          },
          eduExp: {
            title: edu[res.education].title,
            value: res.education
          },
          street: {
            title: res.street
          },
          address: res.address,
          welfares: res.positionWelfares,
          posDes: res.description,
          employmentType: {
            title: res.employmentType == 1 ? '代招' : '直招',
            value: res.employmentType
          },
          workCompany: res.workCompany,
          workCompanyId: res.workCompanyId,
          templateImg: res.entrustPhoto || this.data.templateImg,
          specialActivitys: res.specialActivitys,
          isUpdatePay: false,
          isSoldout: res.usable
        });

        // 渲染悬赏情况 
        if (Object.keys(_reward).length != 0) {
          this.setData({
            isReward: true,
            rewardDeadLine: {
              title: _reward.dayNum,
              value: rewardDeadLineV
            },
            rewardCount: _reward.quantity,
            singleRewardMoney: _reward.money,
            rewardUsed: _reward.totalMoney / _reward.residueMoney,
            rewardRedius: _reward.residueMoney,
            rewardRefundId: _reward.orderId,
            rewardTotal: (_reward.quantity * _reward.money).toFixed(2),
            isSetedReward: true
          })
        } else {
          this.setData({
            isReward: false,
          })
        }

        // 渲染红包情况
        if (Object.keys(redPacket).length != 0) {
          this.setData({
            isRedpacket: true,
            redpacketCount: redPacket.quantity,
            singleRedpacketMoney: redPacket.money,
            redPacketUsed: redPacket.totalMoney / redPacket.residueMoney,
            redPacketRedius: redPacket.residueMoney,
            redPacketRefundId: redPacket.orderId,
            redPacketTotal: (redPacket.quantity * redPacket.money).toFixed(2),
            isSetedRedpacket: true
          })
        } else {
          this.setData({
            isRedpacket: false,
          })
        }

        // 渲染职位福利
        let _temArr = [];
        setTimeout(() => {
          this.data.welfaresArray.forEach((m, i) => {
            this.data.welfares.forEach((e, index) => {
              if (m.title == e) {
                  _temArr.push(String(i));
              }
            })
          })
          this.setData({welfaresValue: _temArr});
        }, 500);

        if (res.redPacket.residueMoney > 0) {
          this.setData({
            isDisableInputRedpack: true
          })
        }
        this.judgeRewardAction(_reward);
        this.getLocation(res.address);
      }
    })
  },

  judgeRewardAction(obj) {
    const nowDate = new Date().getTime();
    const effect = obj.deadline * 1000;
    console.log(effect);
    if (nowDate <= effect && obj.residueMoney > 0) {
      // 还在有效期内
      T.toast({
        id: '#toast',
        text: '该职位现在处于悬赏期内不可进行编辑',
        success: () => {
          wx.navigateBack({
            delta: 1
          })
        }
      });
    } else if (nowDate > effect && obj.residueMoney > 0) {
      // 过期但还没使用完悬赏，禁止设置悬赏/红包份数、单价,可设置有效期
      this.setData({
        isAdRewardDeadline: true,
        isDisableInputRedpack: true
      })
    }
  },

  onUpdateTemplate() {
    let that = this;
    this.data.isOpenUploadImg = true;
    uploadImg(that, 'image', 'resumeImgUpload')
      .then((res) => {
        that.setData({
          templateImg: res,
          isOpenUploadImg: false
        })
      })
  },

  getPopularizelist() {
    T.req({
      url: config.api + 'popularize/list/available',
      method: 'GET',
      data: {
        token: token,
        type: 0
      },
      success: (res) => {
        this.data.initPopularizeList = res;
      }
    })

  },

  getWelfaresArr() {
    T.req({
      loadTitle: '初始化中...',
      url: config.api + 'position/invert_selection',
      method: 'GET',
      data: {
        token: token
      },
      success: (res) => {
        let _tem = [];
        res.welfareVoList.forEach(m => {
          _tem.push({
            title: m.content,
            value: String(m.id),
            select: true
          })
        });
        this.setData({
          welfaresArray: _tem,
          workExpArray: workExp
        });
      }
    })
  },

  onInputPosition(e) {
    this.setData({
      position: e.detail.value
    });
    if (!e.detail.value) return;
    searchPosition(e.detail.value, 0).then(res => {
      this.setData({
        companyList: res,
        isOpen: true
      })
    })
  },

  onSelectPosition(e) {
    let name = e.currentTarget.dataset.name;
    this.setData({
      position: name,
      isOpen: false
    });
  },

  onClosePosition() {
    this.setData({
      isOpen: false
    })
  },

  getLocation(place) {
    getLocation(place).then((res) => {
      if (JSON.stringify(res) == '{}') return;
      if (!place) return;
      this.data.location = res.location;
      let lt = res.location.split(',')[0];
      let la = res.location.split(',')[1];
      this.showMap(lt, la);
    });
  },

  onInputAddress(e) {
    this.setData({
      address: e.detail.value
    });
    this.getLocation(e.detail.value);
  },

  onInputPosDes(e) {
    this.setData({
      posDes: e.detail.value
    });
  },

  onInputRewardCount(e) {
    this.setData({
      rewardCount: e.detail.value,
      rewardTotal: (Number(this.data.singleRewardMoney) * Number(e.detail.value)).toFixed(2),
      isUpdatePay: Number(e.detail.value) > 0 ? true : false
    });
  },

  onInputSingleRewardMoney(e) {
    this.setData({
      singleRewardMoney: e.detail.value,
      rewardTotal: (Number(e.detail.value) * Number(this.data.rewardCount)).toFixed(2),
      isUpdatePay: Number(e.detail.value) > 0 ? true : false
    });
  },

  onInputRedpacketCount(e) {
    this.setData({
      redpacketCount: e.detail.value,
      redPacketTotal: (Number(this.data.singleRedpacketMoney) * Number(e.detail.value)).toFixed(2),
      isUpdatePay: Number(e.detail.value) > 0 ? true : false
    });
  },

  onInputSingleRedpacketMoney(e) {
    this.setData({
      singleRedpacketMoney: e.detail.value,
      redPacketTotal: (Number(e.detail.value) * Number(this.data.redpacketCount)).toFixed(2),
      isUpdatePay: Number(e.detail.value) > 0 ? true : false
    });
  },

  onClickIndustry() {
    this.setData({
      isOpenMap: false,
      isShowPosDes: true
    })
    $wuxSelect('#wux-select-industry').open({
      value: '',
      options: getApp().globalData.industryList,
      onConfirm: (value, index, options) => {
        this.setData({
          isOpenMap: true,
          isShowPosDes: false
        })
        if (index !== -1) {
          this.setData({
            value2: value,
            industry: options[index],
          })
        }
      },
      onCancel: () => {
        this.setData({
          isOpenMap: true,
          isShowPosDes: false
        })
      }
    });
  },

  onClickSalary() {
    this.setData({
      isOpenMap: false,
      isShowPosDes: true
    })
    $wuxSelect('#wux-select-salary').open({
      value: '',
      options: salary,
      onConfirm: (value, index, options) => {
        this.setData({
          isOpenMap: true,
          isShowPosDes: false
        })
        if (index !== -1) {
          this.setData({
            value2: value,
            salary: options[index],
          })
        }
      },
      onCancel: () => {
        this.setData({
          isOpenMap: true,
          isShowPosDes: false
        })
      }
    });
  },

  onClickWorkExp() {
    this.setData({
      isOpenMap: false,
      isShowPosDes: true
    })
    $wuxSelect('#wux-select-workExp').open({
      value: '',
      options: this.data.workExpArray,
      onConfirm: (value, index, options) => {
        this.setData({
          isOpenMap: true,
          isShowPosDes: false
        })
        if (index !== -1) {
          this.setData({
            value2: value,
            workExp: options[index],
          })
        }
      },
      onCancel: () => {
        this.setData({
          isOpenMap: true,
          isShowPosDes: false
        })
      }
    });
  },

  onClickEduExp() {
    this.setData({
      isOpenMap: false,
      isShowPosDes: true
    })
    $wuxSelect('#wux-select-eduExp').open({
      value: '',
      options: edu,
      onConfirm: (value, index, options) => {
        this.setData({
          isOpenMap: true,
          isShowPosDes: false
        })
        if (index !== -1) {
          this.setData({
            value2: value,
            eduExp: options[index],
          })
        }
      },
      onCancel: () => {
        this.setData({
          isOpenMap: true,
          isShowPosDes: false
        })
      }
    });
  },

  onClickStreet() {
    this.setData({
      isOpenMap: false,
      isShowPosDes: true
    })
    $wuxSelect('#wux-select-street').open({
      value: '',
      options: street,
      onConfirm: (value, index, options) => {
        this.setData({
          isOpenMap: true,
          isShowPosDes: false
        })
        if (index !== -1) {
          this.setData({
            value2: value,
            street: options[index],
          })
        }
      },
      onCancel: () => {
        this.setData({
          isOpenMap: true,
          isShowPosDes: false
        })
      }
    });
  },

  onClickWelfares() {
    this.setData({
      isOpenMap: false,
      isShowPosDes: true
    })
    $wuxSelect('#wux-select-welfares').open({
      value: this.data.welfaresValue || '',
      multiple: true,
      options: this.data.welfaresArray,
      onConfirm: (value, index, options) => {
        this.setData({
          welfaresValue: value,
          welfares: index.map((n) => options[n].title),
          isOpenMap: true,
          isShowPosDes: false
        })
      },
      onCancel: () => {
        this.setData({
          isOpenMap: true,
          isShowPosDes: false
        })
      }
    });
  },

  onClickEmploymentType() {
    this.setData({
      isOpenMap: false,
      isShowPosDes: true
    })
    $wuxSelect('#wux-select-employmentType').open({
      value: '',
      options: [{
        title: '直招',
        value: 0
      }, {
        title: '代招',
        value: 1
      }],
      onConfirm: (value, index, options) => {
        this.setData({
          isOpenMap: true,
          isShowPosDes: false
        })
        if (index !== -1) {
          this.setData({
            value2: value,
            employmentType: options[index],
          })
        }
      },
      onCancel: () => {
        this.setData({
          isOpenMap: true,
          isShowPosDes: false
        })
      }
    });
  },

  onClickRrewardDeadLine() {
    $wuxSelect('#wux-select-rewardDeadLine').open({
      value: '',
      options: reward,
      onConfirm: (value, index, options) => {
        if (index !== -1) {
          this.setData({
            value2: value,
            rewardDeadLine: options[index],
          })
        }
      }
    });
  },

  onSelectReward() {
    this.setData({
      isReward: !this.data.isReward
    })
  },

  onSelectRedpacket() {
    this.setData({
      isRedpacket: !this.data.isRedpacket
    })
  },

  onSelectPopularize(e) {
    this.setData({
      isPopularize: !this.data.isPopularize
    });
  },

  onShowPopularizeList(values) {
    if (values.length == 0) return;
    this.setData({
      popularizeCount: values.length
    })
    let _popularize = this.data.initPopularizeList;
    let _newArray = [];
    let _user = [];
    values.forEach(m => {
      _popularize.forEach((e, i) => {
        let _time = T.formatTime(e.date);
        let stamp = new Date(_time.year + '/' + _time.month + '/' + _time.day + ' 00:00:00').getTime();
        if (m == stamp) {
          _newArray.push(e);
          if (e.unoccupied != 0) {
            _user.push(e.date);
          }
        }
      });
    })

    let _temArr = [];
    _user.forEach(m => {
      let _date = T.formatTime(m, '-');
      _temArr.push(_date);
    });

    this.setData({
      popularizeList: _newArray,
      selectedPopularizeDate: _temArr
    });
  },

  onPopularizeDate(e) {
    if (this.data.totalPopularizeCount == 0) {
      T.toast({
        id: '#toast',
        text: '您已经没有剩余推广次数，不能进行推广'
      })
      this.setData({
        isPopularize: false
      });
      return;
    }
    const now = new Date()
    const minDate = now.setDate(now.getDate());
    const maxDate = now.setDate(now.getDate() + 30);
    this.setData({
      isShowPopularize: true,
      isShowCalendar: true
    });
    console.log(this.data.isShowPopularize);
    $wuxCalendar().open({
      value: this.data.wuxCalendarSelected || [],
      minDate: minDate,
      maxDate: maxDate,
      multiple: true,
      onChange: (values, displayValues) => {
        this.data.wuxCalendarSelected = values;
        this.onShowPopularizeList(values);
      },
      onClose: () => {
        this.setData({
          isShowPopularize: false
        });
      }
    });
  },

  onSureSelectPopularize() {
    this.setData({
      isShowCalendar: false,
      isShowPopularize: false
    })
  },

  onPrevStep() {
    this.setData({
      step01: true
    });
  },

  getStep01Data() {
    let obj = {};
    obj.name = this.data.position;
    obj.industryId = this.data.industry.title
    obj.salary = this.data.salary.title;
    obj.candidateRequire = this.data.workExp.title;
    obj.education = this.data.eduExp.title;
    obj.street = this.data.street.title;
    obj.address = this.data.address;
    obj.positionWelfare = this.data.welfares;
    obj.description = this.data.posDes;
    obj.employmentType = this.data.employmentType.title;
    if (this.data.employmentType.value == 1) {
      obj.workCompany = this.data.workCompany;
      obj.entrustPhoto = this.data.templateImg;
    }
    console.log(obj)
    let isError = false;
    for (const k in obj) {
      if (!obj[k] || obj[k] == '请选择') {
        isError = true;
      }
    }
    if (!/^http/.test(obj.entrustPhoto) && this.data.employmentType.value == 1) {
      isError = true;
    }
    if (isError) {
      T.toast({
        id: '#toast',
        text: '还有选项没有填写或者选择,请检查'
      });
    }
    obj.workCompanyId = this.data.workCompanyId;
    obj.location = this.data.location;
    return {
      isError: isError,
      obj: obj
    };
  },

  onNextStep() {
    let _tem = this.getStep01Data();
    // 没问题继续加数据
    if (!_tem.isError) {
      _tem.obj.industryId = this.data.industry.value
      _tem.obj.salary = this.data.salary.value;
      _tem.obj.candidateRequireId = Number(this.data.workExp.value);
      _tem.obj.employmentType = this.data.employmentType.value;
      _tem.obj.education = this.data.eduExp.value;
      this.data.reqParam = _tem.obj;
      this.setData({
        step01: false
      });
    }
  },

  /**
   * 去支付
   * @param pType 支付类型  0：红包 1：悬赏  2：红包+悬赏
   * @param pContent 支付内容
   */
  onPay(pType, pContent) {
    return new Promise((resolve, reject) => {
      let t = 0;
      let reqParam = {
        openid: getApp().globalData.openId,
        body: '支付普通职位{' + this.data.position + '}红包',
        goodsId: this.data.positionId,
        goodsType: 3,
        topUpType: pType,
      }
      Object.assign(reqParam, pContent);
      T.req({
        loadTitle: '请求中...',
        url: config.api + 'pay/wechat/tradepay?token=' + token,
        method: 'POST',
        data: reqParam,
        success: (res) => {
          wx.requestPayment({
            timeStamp: res.timeStamp,
            nonceStr: res.nonceStr,
            package: res.package,
            signType: res.signType,
            paySign: res.paySign,
            success: () => {
              resolve(res.outTradeNo);
              onRecord(res.outTradeNo);
            },
            fail: (err) => {
              console.warn(err);
            }
          })
        }
      })
    });
  },

  /**
   * 新增普通职位获取id
   */
  onFirstCreate() {
    let obj = this.data.reqParam;
    let _reqParam = {
      userHrId: getApp().globalData.userId,
      positionId: 0,
      positionName: obj.name,
      industryId: obj.industryId,
      salary: obj.salary,
      candidateRequireId: obj.candidateRequireId,
      education: obj.education,
      location: obj.location,
      address: obj.address,
      street: obj.street,
      positionWelfare: obj.positionWelfare,
      description: obj.description,
      employmentType: obj.employmentType,
      popularityDate: this.data.isPopularize ? this.data.selectedPopularizeDate : [],
    }

    //  是否代招
    if (obj.employmentType) {
      _reqParam.workCompany = this.data.workCompany;
      _reqParam.workCompanyId = this.data.workCompanyId;
      _reqParam.entrustPhoto = this.data.templateImg;
    } else {
      _reqParam.workCompany = '';
      _reqParam.workCompanyId = 0;
    }

    // 之前是否已经调用过新增接口-如果是，直接调支付
    if (this.data.isCreatePosition) {
      this.onMadePosition();
      return;
    }

    T.req({
      loadTitle: '请求中...',
      url: config.api + 'position?token=' + token,
      method: 'POST',
      data: _reqParam,
      success: (res) => {
        this.data.isCreatePosition = true;
        this.data.positionId = res.positionId;
        this.onMadePosition();
      }
    })
  },


  /**
   * 创建临时普通职位-专场用的
   */
  onSpecialPositionCreate() {
    let obj = this.data.reqParam;
    let _reqParam = {
      userHrId: getApp().globalData.userId,
      positionId: 0,
      positionName: obj.name,
      industryId: obj.industryId,
      salary: obj.salary,
      candidateRequireId: obj.candidateRequireId,
      education: obj.education,
      location: obj.location,
      address: obj.address,
      street: obj.street,
      positionWelfare: obj.positionWelfare,
      description: obj.description,
      employmentType: obj.employmentType,
      popularityDate: this.data.isPopularize ? this.data.selectedPopularizeDate : [],
      specialActivityId: this.data.specialId
    }
    //  是否代招
    if (obj.employmentType) {
      _reqParam.workCompany = this.data.workCompany;
      _reqParam.workCompanyId = this.data.workCompanyId;
      _reqParam.entrustPhoto = this.data.templateImg;
    } else {
      _reqParam.workCompany = '';
      _reqParam.workCompanyId = 0;
    }
    T.req({
      loadTitle: '请求中...',
      url: config.api + 'special_activity/add_temp_position?token=' + token,
      method: 'POST',
      data: _reqParam,
      success: (res) => {
        this.data.positionId = res.positionId;
        this.onMadePosition();
      }
    })
  },

  /**
   * 操作职位成功，跳转到职位列表
   */
  onPositionChange() {
    var pages = getCurrentPages();
    let routes = 0;
    if (this.data.isEdit) {// 如果是从编辑跳转过来，返回跳转路由跳两级
      routes = 1;
    }
    routes = routes || 0;
    if (this.data.isSpecialToCreate) {
      wx.navigateBack({
        delta: 1
      })
      return ;
    }
    if (pages.length > 1) {
      //上一个页面实例对象
      var prePage = pages[pages.length - 2 - routes];
      prePage.data.posList = [];
      prePage.getFulltimeList();
      wx.navigateBack({
        delta: 1 + routes
      })
    }
  },


  /**
   *  判断支付类型
   */
  onMadePosition() {
    let obj = this.data.reqParam;
    let _reqParam = {
      reward: {},
      redpack:{}
    };
    // 是否设置悬赏
    if (this.data.isReward) {
      _reqParam.reward.money = obj.reward.money;
      _reqParam.reward.quantity = obj.reward.quantity;
      _reqParam.reward.dayNum = obj.reward.dayNum;
    }

    // 是否设置红包
    if (this.data.isRedpacket) {
      _reqParam.redpack.money = obj.redPacket.money;
      _reqParam.redpack.quantity = obj.redPacket.quantity;
    }

    if (!this.data.isEdit || this.data.isUpdatePay) { // 新增职位时或者(编辑时)悬赏、红包用完并且更新了
      // 再判断是否选择设置悬赏或者面试红包
      if (this.data.isReward && this.data.isRedpacket) {
        this.onPay(2, {reward: _reqParam.reward,redpack: _reqParam.redpack}).then(_orderId => {
          // 支付状态查询
          payStatus(_orderId).then(() => {
            T.toast({ id: '#toast', text:'操作成功', success: () => {
              this.onPositionChange();
            }})
          })
        })
        return ;
      }

      // 悬赏
      if (this.data.isReward) {
        this.onPay(1, { reward: _reqParam.reward}).then(_orderId => {
          // 支付状态查询
          payStatus(_orderId).then(() => {
            T.toast({
              id: '#toast', text: '操作成功', success: () => {
                this.onPositionChange();
              }
            })
          })
        })
        return;
      }

      // 红包
      if (this.data.isRedpacket) {
        this.onPay(0, { redpack: _reqParam.redpack}).then(_orderId => {
          // 支付状态查询
          payStatus(_orderId).then(() => {
            T.toast({
              id: '#toast', text: '操作成功', success: () => {
                this.onPositionChange();
              }
            })
          })
        })
        return;
      }
      // 普通职位-不涉及悬赏与红包
      T.toast({
        id: '#toast', text: '操作成功', success: () => {
            this.onPositionChange();
        }
      })
    } else { 
      // 普通职位-不涉及悬赏与红包
      T.toast({
        id: '#toast', text: '操作成功', success: () => {
          this.onPositionChange();
        }
      })
    }
  },

  onOperation() {
    let rewardObj = {
      dayNum: this.data.rewardDeadLine.title,
      quantity: Number(this.data.rewardCount),
      money: Number(this.data.singleRewardMoney)
    };
    let redpacketObj = {
      quantity: Number(this.data.redpacketCount),
      money: Number(this.data.singleRedpacketMoney)
    };


    if (/resource/.test(this.data.templateImg) && this.data.employmentType.value == 1) {
      T.toast({
        id: '#toast',
        text: '请上传委托书照片'
      });
      return;
    }

    if (this.data.isReward) { // 悬赏职位
      for (const k in rewardObj) {
        if (rewardObj[k] == '请选择' || rewardObj[k] === 0) {
          T.toast({
            id: '#toast',
            text: '请设置悬赏相关数值'
          });
          return;
        }
      }
    }
    if (this.data.isRedpacket) { // 面试红包
      for (const k in redpacketObj) {
        // todo
        // if (redpacketObj[k] === 0 || (k == 'money' && redpacketObj[k] < 10)) {
        if (redpacketObj[k] === 0) {
          T.toast({
            id: '#toast',
            text: '请设置面试红包相关数值且单价须大于10'
          });
          return;
        }
      }
    }

    if (this.data.isPopularize) { // 推广
      if (this.data.selectedPopularizeDate.length == 0) {
        T.toast({
          id: '#toast',
          text: '请选择推广日期'
        });
        return;
      }
    }
    rewardObj.dayNum = Number(this.data.rewardDeadLine.value);
    Object.assign(this.data.reqParam, {
      reward: rewardObj,
      redPacket: redpacketObj
    })

    console.log(this.data.reqParam);

    if (this.data.isSpecialToCreate) { // 从专场选择新建职位跳转过来
      this.onSpecialPositionCreate();
      return;
    }
    if (!this.data.isEdit) { // 是新增职位才需要调用创建职位接口
      this.onFirstCreate();
    } else {
      this.onMadePosition();
    }

  },

  /**
   * 编辑普通职位： 更新-支付(如果有支付的话)
   */
  onEditPosition() {
    let obj = this.data.reqParam;

    let reqParam = {
      positionId: Number(this.data.positionEditId),
      userHrId: getApp().globalData.userId,
      positionName: obj.name,
      industryId: obj.industryId,
      salary: obj.salary,
      candidateRequireId: obj.candidateRequireId,
      education: obj.education,
      location: obj.location,
      street: obj.street,
      address: obj.address,
      positionWelfare: obj.positionWelfare,
      description: obj.description,
      employmentType: obj.employmentType,
      popularize: this.data.isPopularize ? this.data.selectedPopularizeDate : []
    }
    if (obj.employmentType == 1) {
      reqParam.workCompany = obj.workCompany;
      reqParam.workCompanyId = obj.workCompanyId;
      reqParam.entrustPhoto = obj.entrustPhoto;
    }
    
    reqParam.effectiveDateEnum = obj.dayNum || 0;
    console.log(this.data.reqParam)
    T.req({
      loadTitle: '请求中...',
      url: config.api + 'position?token=' + token,
      method: 'PUT',
      data: reqParam,
      success: (res) => {
         this.onMadePosition(); 
      }
    })
  },

  onOperationEdit() {
    let _tem = this.getStep01Data();
    // 没问题继续加数据
    if (!_tem.isError) {
      _tem.obj.industryId = this.data.industry.value
      _tem.obj.salary = this.data.salary.value;
      _tem.obj.candidateRequireId = this.data.workExp.value;
      _tem.obj.employmentType = this.data.employmentType.value;
      _tem.obj.education = this.data.eduExp.value;
      this.data.reqParam = _tem.obj;
      this.onEditPosition();
    }
  },


  /**
   * 发起退款请求
   */
  onSubmitRefund() {
    let param = {
      token: token,
    }
    console.log(param);
    T.req({
      loadTitle: '提交中...',
      url: config.api + 'pay/wechat/refund?' + T.param(param),
      method: 'POST',
      data: {
        refundFee: this.data.refundMoney,
        outTradeNo: this.data.oId
      },
      success: (res) => {
        T.toast({
          id: '#toast', text: '申请成功', success: () => {
            wx.navigateBack({
              delta: 1
            })
          }
        });
      }
    })
  },

  /**
   * 申请退款
   */
  onRefund(e) {
    let id = e.currentTarget.dataset.id;
    let type = e.currentTarget.dataset.type;
    T.req({
      url: config.api + 'center/userinfo',
      method: 'GET',
      data: {
        token: token
      },
      success: (res) => {
        let _str = '';
        if (this.data.rewardRedius) {
          _str += '剩余悬赏金额';
        }
        if (this.data.redPacketRedius) {
          _str += '、剩余面试红包金额';
        }
        console.log(Number(this.data.rewardRedius || 0), Number(this.data.redPacketRedius || 0));
        this.setData({
          refundContent: _str,
          refundMethod: res.name,
          refundMoney: Number(this.data.rewardRedius || 0) + Number(this.data.redPacketRedius || 0),
          isShowRefundShade: true,
        });
      }
    })
  },

  onHideRefundShade() {
    this.setData({ isShowRefundShade: false });
  },

  /**
   * 下架
   */
  onSoldOut() {
    let param = {
      token: token,
      id: this.data.positionEditId
    }
    T.req({
      loadTitle: '请求中...',
      url: config.api + 'position/soldout?' + T.param(param),
      method: 'PUT',
      success: (res) => {
        T.toast({id:'#toast', text:'下架成功',success: () => {
          this.onPositionChange();
        } })
      }
    })
  },

  onRewardDesc() {
    wx.navigateTo({
      url: '/pages/rule-state/reward/index',
    })
  },

  onRedpackDesc() {
    wx.navigateTo({
      url: '/pages/rule-state/redpack/index',
    })
  }
})